package com.diandiansong.app.ui.user;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.widget.EditText;

import com.diandiansong.AppUpdateManager;
import com.diandiansong.app.App;
import com.diandiansong.app.R;
import com.diandiansong.app.entity.LoginInfo;
import com.diandiansong.app.event.FINISH;
import com.diandiansong.app.ui.Main;
import com.diandiansong.app.ui.base.BaseAct;
import com.diandiansong.app.utils.A;
import com.diandiansong.app.utils.Api;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;

import butterknife.BindView;
import butterknife.OnClick;
import diandiansong.library.http.okhttputils.OkHttpUtils;
import diandiansong.library.http.okhttputils.callback.StringCallback;
import diandiansong.library.utils.CCallBack;
import okhttp3.Call;

import static com.diandiansong.app.wxapi.WXEntryActivity.APP_ID;
import static com.diandiansong.app.wxapi.WXEntryActivity.APP_SEC;

/**
 * 登录
 */
public class Login extends BaseAct {

    public static void start(Context context) {
        Intent starter = new Intent(context, Login.class);
        context.startActivity(starter);
    }

    @BindView(R.id.et_phone)
    EditText mEtPhone;
    @BindView(R.id.et_pwd)
    EditText mEtPwd;

    private IWXAPI api;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        addContentView(R.layout.user_login);
        initTitle("登录");
        new AppUpdateManager(this, Api.APP_UPDATE_URL_USER, false,mEtPwd).checkUpdate();
        //账号：13735567661     密码：123456
        if (App.DEBUG) {
            mEtPhone.setText("13212312311");
            mEtPwd.setText("123123");
        }
//        mEtPhone.setText("13735567661");
//        mEtPwd.setText("123456");

        String phone = LoginInfo.getPhone(getActivity());
        String pwd = LoginInfo.getPwd(getActivity());
        if (phone != null && phone.length() > 0) {
            mEtPhone.setText(phone);
            mEtPwd.setText(pwd);
        }

        if (LoginInfo.hasToken(getActivity())) {
            Api.TOKEN = LoginInfo.getToken(getActivity());
            Main.start(getActivity());
            finish();
            return;
        }

        api = WXAPIFactory.createWXAPI(this, APP_ID);
        api.registerApp(APP_ID);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @OnClick(R.id.do_login)
    public void onMDoLoginClicked() {
        final String phone = getText(mEtPhone);
        final String pwd = getText(mEtPwd);
        A.login(phone, pwd, this, new CCallBack<LoginInfo>() {
            @Override
            public void onSuccess(LoginInfo o) {
                LoginInfo.saveToken(getActivity(), o.getData().getToken());
                Api.TOKEN = o.getData().getToken();
                Main.start(getActivity());
                LoginInfo.savePhone(getActivity(), phone);
                LoginInfo.savePwd(getActivity(), pwd);

                finish();
            }

            @Override
            public void onFailure(int code, String msg) {
                toast(msg);
            }
        });
    }

    @OnClick(R.id.do_login_with_wechat)
    public void onMDoLoginWithWechatClicked() {
        SendAuth.Req req = new SendAuth.Req();
        req.scope = "snsapi_userinfo";
        req.state = "wechat_sdk_demo_test";
        api.sendReq(req);
    }

    @OnClick(R.id.go_register)
    public void onMGoRegisterClicked() {
        RegisterStep1.start(getActivity(), null);
    }

    @OnClick(R.id.go_pwd)
    public void onMGoPwdClicked() {
        ForgetPwd.start(getActivity());
    }

    public static class WeixinCode {
        public String code;

        public WeixinCode(String code) {
            this.code = code;
        }
    }

    public static void doWeixinCode(String code) {
        EventBus.getDefault().post(new WeixinCode(code));
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void receiveWeixinCode(WeixinCode weixinCode) {
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + APP_ID + "&secret=" + APP_SEC +
                "&code=" + weixinCode.code + "&grant_type=authorization_code";

        onLoading();
        OkHttpUtils.get().url(url).build().execute(new StringCallback() {
            @Override
            public void onError(String response, Call call, Exception e, int id) {
                toast("微信通讯异常");
                onLoaded();
            }

            @Override
            public void onResponse(String response, int id) {
                onLoaded();
                logger.d("onResponse() called with: " + "response = [" + response + "], id = [" + id + "]");

                String access = null;
                String openId = null;
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    access = jsonObject.getString("access_token");
                    openId = jsonObject.getString("openid");
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (openId != null) {
                    final String finalOpenId = openId;
                    A.openid(openId, Login.this, new CCallBack<LoginInfo>() {
                        @Override
                        public void onSuccess(LoginInfo o) throws Exception {
                            LoginInfo.Data data = o.getData();
                            if (data != null) {
                                String token = data.getToken();
                                if (token != null && !token.isEmpty()) {
                                    //正常用户
                                    LoginInfo.saveToken(getActivity(), o.getData().getToken());
                                    Api.TOKEN = o.getData().getToken();
                                    Main.start(getActivity());
                                    finish();

                                } else {
                                    RegisterStep1.start(getActivity(), finalOpenId);
                                }

                            } else {
                                toast("获取微信授权失败");
                                RegisterStep1.start(getActivity(), null);
                            }
                        }

                        @Override
                        public void onFailure(int code, String msg) {
                            toast("获取微信授权失败");
                            RegisterStep1.start(getActivity(), null);
                        }
                    });

                } else {
                    toast("获取微信授权失败");
                    RegisterStep1.start(getActivity(), null);
                }
            }
        });

    }

    @Override
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void do401(FINISH f) {
        //just show me
    }
}
